package drds.plus.datanode.executor;

import drds.plus.datanode.configuration.DataSourceWrapper;
import drds.plus.datanode.select.equity_manager_select.GroupNotAvaliableException;
import drds.plus.datasource.exception_sorter.ExceptionSorter;

import java.sql.SQLException;
import java.util.List;

public class ExecutorWrapper<T> implements Executor<T> {

    private final List<SQLException> historySQLExceptionList;
    private final Executor<T> executor;

    public ExecutorWrapper(Executor<T> executor, List<SQLException> historySQLExceptionList) {
        this.executor = executor;
        this.historySQLExceptionList = historySQLExceptionList;
    }

    public T onSqlException(List<SQLException> sqlExceptionList, ExceptionSorter exceptionSorter, Object... args) throws SQLException {
        Exception last = sqlExceptionList.get(sqlExceptionList.size() - 1);
        if (last instanceof GroupNotAvaliableException) {
            if (sqlExceptionList.size() > 1) {
                sqlExceptionList.remove(sqlExceptionList.size() - 1);
            }
            historySQLExceptionList.addAll(sqlExceptionList);
            throw (GroupNotAvaliableException) last;
        } else {
            return executor.onSqlException(sqlExceptionList, exceptionSorter, args);
        }
    }

    public T createConnectionWrapperAndExecute(DataSourceWrapper dataSourceWrapper, Object... args) throws SQLException {
        return executor.createConnectionWrapperAndExecute(dataSourceWrapper, args);
    }
}
